﻿///////////////////////////////////////////////////
/// $Id$
/// $Date$
/// $Author$
/// $Revision$
/// E-mail: tonyjobmails@gmail.com
/// filename: Mutex.h
/// function: 互斥量定义
///////////////////////////////////////////////////

#ifndef __MUTEX__H
#define __MUTEX__H

#include <pthread.h>

class CCond;

class CMutex
{
	public:
		/***************************************************
		/// 互斥锁类型定义
		enum
		{
			PTHREAD_MUTEX_TIMED_NP,
			PTHREAD_MUTEX_RECURSIVE_NP,
			PTHREAD_MUTEX_ERRORCHECK_NP,
			PTHREAD_MUTEX_ADAPTIVE_NP
		#ifdef __USE_UNIX98
			,
			PTHREAD_MUTEX_NORMAL = PTHREAD_MUTEX_TIMED_NP,
			PTHREAD_MUTEX_RECURSIVE = PTHREAD_MUTEX_RECURSIVE_NP,
			PTHREAD_M UTEX_ERRORCHECK = PTHREAD_MUTEX_ERRORCHECK_NP,
			PTHREAD_MUTEX_DEFAULT = PTHREAD_MUTEX_NORMAL
		#endif
		#ifdef __USE_GNU
			, PTHREAD_MUTEX_FAST_NP = PTHREAD_MUTEX_TIMED_NP
		#endif
		};
		****************************************************/

		friend class CCond;

		CMutex(int kind = PTHREAD_MUTEX_NORMAL)
		{
			pthread_mutexattr_t attr;
			::pthread_mutexattr_init(&attr);
			::pthread_mutexattr_settype(&attr, kind);
			pthread_mutex_init(&this->mutex, &attr);
			/// pthread_mutexattr_destroy(&attr);
		}

		virtual ~CMutex()
		{
			::pthread_mutex_destroy(&this->mutex);
		}

		/// 加锁
		inline void lock()
		{
			::pthread_mutex_lock(&this->mutex);
		}

		/// 解锁
		inline void unlock()
		{
			::pthread_mutex_unlock(&this->mutex);
		}

	private:
		pthread_mutex_t mutex;
};

/// 自动锁
class CAutoMutex
{
	public:
		CAutoMutex()
		{
			this->_M_mutex.lock();
		}

		~CAutoMutex()
		{
			this->_M_mutex.unlock();
		}

	private:
		CMutex _M_mutex;
};

#endif	/// __MUTEX__H
